<template>
  <div class="register">
    <div style="height: 1px;width: 100%"></div>
    <div class="formWrap">
      <p>用户注册</p>
      <a-form-model :model="form" :wrapper-col="{ span: 10 }" :rules="rules" ref="ruleForm">
        <a-form-model-item label="" prop="phone">
          <a-input v-model="form.phone" style="text-align: left" size="large" placeholder="输入手机号或者邮箱号" />
        </a-form-model-item>
        <a-form-model-item label="" prop="checkCode">
          <a-input v-model="form.checkCode" size="large" placeholder="请输入验证码">
            <a slot="addonAfter" @click="getMessageNum" :disabled="disabled">
              {{ sendText }}
            </a>
          </a-input>
        </a-form-model-item>
        <a-form-model-item label="" prop="password">
          <a-input-password v-model="form.password" size="large" placeholder="8到20位数字字母组合" />
        </a-form-model-item>
        <a-form-model-item label="" prop="secondPassword">
          <a-input-password v-model="form.secondPassword" size="large" placeholder="请再次输入密码" />
        </a-form-model-item>
        <a-form-model-item label="" prop="referralCode">
          <a-input v-model="form.referralCode" size="large" placeholder="推荐码" />
        </a-form-model-item>
        <a-form-model-item>
          <a-button type="primary" size="large" style="width: 250px;" @click="checkReferrCode('ruleForm')">注册</a-button>
        </a-form-model-item>
      </a-form-model>
    </div>
    <div style="height: 1px;width: 100%"></div>
  </div>
</template>

<script>
import { registerUser, sendRegisterEmailCode, sendRegisterSmsCode, checkCode } from '../serves';

export default {
  name: 'register',
  data() {
    const validatePhone = (rule, value, callback) => {
      let reg1 = /^1[0-9]{10}$/;
      let reg2 = /^([a-zA-Z\d])(\w|)+@[a-zA-Z\d]+\.[a-zA-Z]{2,4}$/;
      if (value === '') {
        callback(new Error('请输入手机号码或邮箱号！'));
      } else if (!reg1.test(value) && !reg2.test(value)) {
        callback(new Error('手机号码或邮箱错误，请重新输入！'));
      } else {
        callback();
      }
    };
    const validatePassWord = (rule, value, callback) => {
      let reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$/;
      if (value === '') {
        callback(new Error('密码不能为空！'));
      } else if (!reg.test(value)) {
        callback(new Error('8到20位数字字母组合'));
      } else {
        callback();
      }
    };
    const validateSecPassWord = (rule, value, callback) => {
      let reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$/;
      if (value === '') {
        callback(new Error('密码不能为空！'));
      } else if (!reg.test(value)) {
        callback(new Error('8到20位数字字母组合'));
      } else if (value != this.form.password) {
        callback(new Error('两次密码输入不一致，请重新输入！'));
      } else {
        callback();
      }
    };
    return {
      form: {
        phone: '',
        nickname: '',
        password: '',
        secondPassword: '',
        checkCode: '',
        referralCode: ''
      },
      sendText: '获取验证码',
      disabled: false,
      timer: null,
      rules: {
        phone: [
          {
            validator: validatePhone,
            trigger: 'change'
          }
        ],
        password: [
          {
            required: true,
            validator: validatePassWord,
            trigger: 'change'
          }
        ],
        secondPassword: [
          {
            required: true,
            validator: validateSecPassWord,
            trigger: 'change'
          }
        ],
        checkCode: [
          {
            message: '验证码不能为空！',
            required: true,
            trigger: 'change'
          }
        ],
        referralCode: [
          {
            message: '推荐码不能为空！',
            required: true,
            trigger: 'change'
          }
        ]
      }
    };
  },
  mounted() {
    if (this.$route.query.inviteCode) {
      this.form.referralCode = this.$route.query.inviteCode;
    }
  },
  methods: {
    setTime(num) {
      if (num <= 1) {
        this.sendText = `重新发送`;
        this.disabled = false;
        clearTimeout(this.timer);
        return false;
      } else {
        this.disabled = true;
        num--;
      }
      this.sendText = `${num}s后重新发送`;
      this.timer = setTimeout(() => {
        this.setTime(num);
      }, 1000);
    },
    getMessageNum() {
      if (!this.form.phone) {
        this.$message.warning('手机号或邮箱号不能为空！');
        return;
      }
      this.sendText = `60s后重新发送`;
      this.disabled = true;
      this.setTime(60);
      let params = {
        data: this.form.phone
      };
      if (this.form.phone.indexOf('.') != -1) {
        sendRegisterEmailCode(params).then((res) => {
          if (res.status == 200 && res.data.status.code == 200) {
            this.$message.success('发送成功！');
          } else {
            this.$message.warning(res.data.message);
          }
        });
      } else {
        sendRegisterSmsCode(params).then((res) => {
          if (res.status == 200 && res.data.status.code == 200) {
            this.$message.success('发送成功！');
          } else {
            this.$message.warning(res.data.message);
          }
        });
      }
    },
    checkReferrCode(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let params = {
            data: this.form.referralCode
          };
          checkCode(params).then((res) => {
            if (res.status == 200 && res.data.status.code == 200) {
              this.$message.success('推荐码可以正常使用');
              this.registerUser();
            } else {
              this.$message.warning('推荐码不存在，请重新输入');
            }
          });
        }
      });
    },
    registerUser() {
      let params = {};
      if (this.form.phone.indexOf('.') != -1) {
        params = {
          email: this.form.phone,
          nickname: this.form.phone.substring(this.form.phone.length - 4),
          password: this.form.password,
          checkCode: this.form.checkCode,
          referralCode: this.form.referralCode
        };
      } else {
        params = {
          phone: this.form.phone,
          nickname: this.form.phone.substring(this.form.phone.length - 4),
          password: this.form.password,
          checkCode: this.form.checkCode,
          referralCode: this.form.referralCode
        };
      }
      registerUser(params).then((res) => {
        if (res.status == 200 && res.data.status.code == 200) {
          this.$message.success('注册成功，请登录');
          setTimeout(() => {
            this.$router.push('login');
          }, 1000);
        } else {
          this.$message.warn(res.data.message);
        }
      });
    }
  }
};
</script>

<style scoped lang="scss">
.register {
  background-color: #f2f2f2;

  .formWrap {
    margin: 100px 300px;
    background-color: #fff;
    padding: 50px;

    > p {
      font-size: 26px;
      font-weight: 700;
    }

    .ant-form-item {
      display: flex;
      justify-content: center;
    }

    .ant-input-group-compact {
      display: flex;
    }
  }
}

@media screen and (max-width: 800px) {
  .register {
    .formWrap {
      margin: 10px;
      background-color: #fff;
      padding: 100px 10px;

      > p {
        font-size: 20px;
      }
    }
  }
}
</style>
